﻿using System;
using System.Threading;
using NUnit.Framework;
using Smith.AMC;

namespace MemcachedClientTests
{
    [TestFixture]
    public class MecachedClientSetTest
    {
        [Test]
        public void SetShouldOverwriteWhatIsInTheServer()
        {
            IMemcachedClient client = new MemcachedClient();
            ICacheItem<string> cacheItem = new CacheItem<string>
                                      {
                                          CacheKey = "setTest",
                                          Value = "This is the initial value",
                                          LifeTime = TimeSpan.FromMinutes(20)
                                      };


            TestHelper.SetValueInServer(client, cacheItem);

            cacheItem.Value = "This is the new Value";
            ManualResetEvent evt = new ManualResetEvent(false);
            bool success = false;
            
            client.BeginSet(cacheItem, ar =>
            {
                ManualResetEvent evtInner = (ManualResetEvent)ar.AsyncState;
                try
                {
                    success = client.EndSet<string>(ar);
                }
                finally
                {
                    evtInner.Set();
                }

            }, evt);

            evt.WaitOne();

            Assert.That(success, Is.True);
            string valueFromServer = TestHelper.GetValueFromServer<string>(client, cacheItem.CacheKey);
            Assert.That(valueFromServer, Is.EqualTo(cacheItem.Value));
                
        }

    }
}
